package org.linlinjava.litemall.admin.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.linlinjava.litemall.admin.beans.Constants;
import org.linlinjava.litemall.admin.beans.dto.AdminOrderAcceptAuditMerchandiseVo;
import org.linlinjava.litemall.admin.beans.dto.AdminOrderAcceptAuditVo;
import org.linlinjava.litemall.admin.beans.dto.PurchaseDto;
import org.linlinjava.litemall.admin.beans.dto.PurchaseItemDto;
import org.linlinjava.litemall.admin.beans.enums.AdminOrderStatusEnum;
import org.linlinjava.litemall.admin.beans.enums.AdminPayStatusEnum;
import org.linlinjava.litemall.admin.beans.enums.PromptEnum;
import org.linlinjava.litemall.admin.beans.vo.AdminOrderMerchandiseVo;
import org.linlinjava.litemall.admin.beans.vo.AdminOrderVo;
import org.linlinjava.litemall.admin.beans.vo.ShopOrderVo;
import org.linlinjava.litemall.admin.erp.client.DepotClient;
import org.linlinjava.litemall.admin.erp.rq.PurchaseDepotItem;
import org.linlinjava.litemall.admin.erp.rq.PurchaseInfo;
import org.linlinjava.litemall.admin.erp.rq.PurchaseRQ;
import org.linlinjava.litemall.admin.util.AdminResponseEnum;
import org.linlinjava.litemall.admin.util.RandomUtils;
import org.linlinjava.litemall.admin.vo.adminorder.AdminOrderRespVO;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallAdminOrder;
import org.linlinjava.litemall.db.domain.LitemallAdminOrderMerchandise;
import org.linlinjava.litemall.db.domain.LitemallMerchandise;
import org.linlinjava.litemall.db.domain.LitemallMerchandiseLog;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShopMerchandise;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.PageTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 管理员管理订单服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Slf4j
@Service
@Transactional
public class AdminAdminOrderService {

    /**
     * 管理订单服务
     */
    @Autowired
    private LitemallAdminOrderService adminOrderService;
    @Autowired
    private LitemallAdminService litemallAdminService;
    /**
     * 管理订单商品服务
     */
    @Autowired
    private LitemallAdminOrderMerchandiseService adminOrderMerchandiseService;
    /**
     * 商品服务
     */
    @Autowired
    private LitemallMerchandiseService merchandiseService;
    /**
     * 店服务
     */
    @Autowired
    private LitemallShopService shopService;
    /**
     * 商品日志服务
     */
    @Autowired
    private LitemallMerchandiseLogService merchandiseLogService;
    /**
     * 商店商品服务
     */
    @Autowired
    private LitemallShopMerchandiseService shopMerchandiseService;

    @Autowired
    private LitemallAdminOrderService litemallAdminOrderService;

    @Autowired
    private LitemallAdminOrderMerchandiseService litemallAdminOrderMerchandiseService;

    @Autowired
    private LitemallMerchandiseService litemallMerchandiseService;

    @Autowired
    private DepotClient depotClient;

    @Value("${erp.depot.purchase.url}")
    private String depotPurchaseUrl ;
    /**
     * 列表
     * 调货申请列表
     *
     * @param orderStatus 订单状态
     * @param startDate   开始日期
     * @param endDate     结束日期
     * @param orderSn     订单sn
     * @param userName    用户名
     * @param address     地址
     * @param shopId      商店id
     * @param page        页面
     * @param limit       限制
     * @param sort        排序
     * @param order       订单
     * @return {@link Object}
     */
    public Object list(Integer orderStatus,String startDate, String endDate, String orderSn, String userName, String address,
                       Integer shopId,
                       Integer page, Integer limit, String sort, String order,Integer serverType) {
        LocalDate startTimes = LocalDate.now();
        LocalDate endTimes = LocalDate.now();
        if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTimes = LocalDate.parse(startDate, timeDtf);
            endTimes = LocalDate.parse(endDate, timeDtf);
        }
        List<Integer> orderStatusEnums = orderStatus==null?Arrays.asList(AdminOrderStatusEnum.P_5.getCode()):
                Arrays.asList(orderStatus);
        IPage<LitemallAdminOrder> adminOrders = adminOrderService.page(new Page<>(page,limit),Wrappers.lambdaQuery(LitemallAdminOrder.class)
                .eq(shopId != null, LitemallAdminOrder::getShopId, shopId)
                .eq(serverType != null, LitemallAdminOrder::getServiceType, serverType)
                .between(startDate != null && endDate != null, LitemallAdminOrder::getUpdateTime, startTimes.atTime(LocalTime.MIN), endTimes.atTime(LocalTime.MAX))
                .eq(LitemallAdminOrder::getDeleted, 0)
                .in(LitemallAdminOrder::getOrderStatus,orderStatusEnums)
                .orderByDesc(LitemallAdminOrder::getAddTime)
        );
        List  adminOrderRespList = CollStreamUtil.toList(adminOrders.getRecords(),adminOrder->{
            AdminOrderRespVO bean = BeanUtil.toBean(adminOrder, AdminOrderRespVO.class);
            LitemallAdmin admin = litemallAdminService.findById(adminOrder.getAdminId());
            bean.setNikeName(admin.getNickName());
            return bean;
        });
        adminOrders.setRecords(adminOrderRespList);
        return ResponseUtil.okPage(adminOrders);
    }
    public Object merchandiseList(Integer orderStatus,String startDate, String endDate,Integer shopId,
                       Integer page, Integer limit,Integer serverType) {
        LocalDate startTimes = LocalDate.now();
        LocalDate endTimes = LocalDate.now();
        if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTimes = LocalDate.parse(startDate, timeDtf);
            endTimes = LocalDate.parse(endDate, timeDtf);
        }
        List<Integer> orderStatusEnums = orderStatus==null?Arrays.asList(AdminOrderStatusEnum.P_1.getCode(), AdminOrderStatusEnum.P_2.getCode(), AdminOrderStatusEnum.P_3.getCode(),
               AdminOrderStatusEnum.P_4.getCode(), AdminOrderStatusEnum.P_6.getCode(),AdminOrderStatusEnum.P_7.getCode(),AdminOrderStatusEnum.P_8.getCode(),AdminOrderStatusEnum.P_9.getCode()):
                Arrays.asList(orderStatus);
        IPage<LitemallAdminOrder> adminOrders = adminOrderService.page(new Page<>(page,limit),Wrappers.lambdaQuery(LitemallAdminOrder.class)
                .eq(shopId != null, LitemallAdminOrder::getShopId, shopId)
                .eq(serverType != null, LitemallAdminOrder::getServiceType, serverType)

                .between(startDate != null && endDate != null, LitemallAdminOrder::getUpdateTime, startTimes.atTime(LocalTime.MIN), endTimes.atTime(LocalTime.MAX))
                .eq(LitemallAdminOrder::getDeleted, 0)
                .in(LitemallAdminOrder::getOrderStatus, orderStatusEnums)
                .orderByDesc(LitemallAdminOrder::getAddTime)
        );
        List<AdminOrderRespVO> adminOrderRespList = CollStreamUtil.toList(adminOrders.getRecords(),adminOrder->{
            AdminOrderRespVO bean = BeanUtil.toBean(adminOrder, AdminOrderRespVO.class);
            LitemallAdmin admin = litemallAdminService.findById(adminOrder.getAdminId());
            bean.setNikeName(admin.getNickName());
            return bean;
        });
        return ResponseUtil.okPage(adminOrders,adminOrderRespList);
    }




    /**
     * 订单申请
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link Object}
     */
    public Object orderApplying(AdminOrderVo adminOrderVo) {

        if(ObjectUtils.isEmpty(adminOrderVo.getMerchandiseId()) || ObjectUtils.isEmpty(adminOrderVo.getShopId())
                || ObjectUtils.isEmpty(adminOrderVo.getUserId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        //查询货品信息
        LitemallMerchandise merchandise = merchandiseService.findById(adminOrderVo.getMerchandiseId());
        //新增订单
        LitemallAdminOrder adminOrder = saveAdminOrder(adminOrderVo, merchandise);
        //新增订单货品
        saveAdminOrderMerchandise(adminOrderVo, merchandise, adminOrder);
        //扣除货品剩余数量
        LitemallMerchandise m = new LitemallMerchandise();
        m.setId(adminOrderVo.getMerchandiseId());
        m.setNumber(merchandise.getNumber()-adminOrderVo.getNumber());
        merchandiseService.updateById(m);
        //保存日志
        adminOrderVo.setOrderSn(adminOrder.getOrderSn());
        adminOrderVo.setAdminOrderId(adminOrder.getId());
        adminOrderVo.setOrderPrice(adminOrder.getOrderPrice());
        this.saveMerchandiseLog(adminOrderVo, Constants.ORDER_APPLYING);

        return ResponseUtil.ok();
    }

    /**
     * 订单通过
     * 同意调货
     *
     * @param id     id
     * @param remark 备注
     * @return {@link Object}
     */
    public Object orderPass(Integer id, String remark) {
        if(ObjectUtils.isEmpty(id)){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        LitemallAdminOrder order = adminOrderService.queryById(id);
 	   	order.setOrderStatus(AdminOrderStatusEnum.P_2.getCode().byteValue());
 	   	adminOrderService.update(order);
 	   	//保存日志
 	   	saveMerchandiseLog(order, Constants.ORDER_PASS, remark);

        return ResponseUtil.ok();
    }
    @Async
    public void erpPurchase(LitemallAdminOrder order) {
        PurchaseRQ rq = new PurchaseRQ();
        //设置采购的基本信息
        PurchaseInfo info = new PurchaseInfo();
        info.setDefaultNumber(order.getOrderSn());
        LitemallShop shop = shopService.findById(order.getShopId());
        String erpCode = shop.getErpCode();
        if(org.apache.commons.lang3.StringUtils.isBlank(erpCode)) {
            log.info("店铺["+ shop.getName() + "]未绑定erp店铺编码，不可发起采购");
            return;
        }
        info.setOrganCode(erpCode);
        info.setRemark(order.getOrderRemark());
        info.setTotalPrice(order.getActualPrice());
        rq.setInfo(JSONObject.toJSONString(info));

        List<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = litemallAdminOrderMerchandiseService.querybyAdminOrderId(order.getId());
        if(litemallAdminOrderMerchandises != null){
            //设置需要采购的商品
            List<PurchaseDepotItem> collect = litemallAdminOrderMerchandises.stream().map(item -> {
                Integer merchandiseId = item.getMerchandiseId();
                LitemallMerchandise litemallMerchandise = litemallMerchandiseService.findById(merchandiseId);
                PurchaseDepotItem depot = new PurchaseDepotItem();
                depot.setBarCode(litemallMerchandise.getMerchandiseSn());
                depot.setUnit(litemallMerchandise.getUnit());
                depot.setOperNumber(String.valueOf(item.getNumber()));
                return depot;
            }).collect(Collectors.toList());
            rq.setInserted(JSONArray.toJSONString(collect));
        }

        try {
            //得到订单编号保存到数据库
            String number = depotClient.addDepotHeadAndDetail(rq, depotPurchaseUrl);
            if(org.apache.commons.lang3.StringUtils.isNotBlank(number)) {
                //保存单据编号，修改订单状态
                LitemallAdminOrder update = new LitemallAdminOrder();
                update.setId(order.getId());
                update.setErpOrderSn(number);
                update.setOrderStatus(AdminOrderStatusEnum.P_3.getCode().byteValue());
                litemallAdminOrderService.update(update);

                /**
                 * 保存日志
                 */
                LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
                merchandiseLog.setAdminOrderId(order.getId());
                merchandiseLog.setOrderSn(order.getOrderSn());
                merchandiseLog.setContent(Constants.ERP_PURCHASE);
                merchandiseLog.setShopId(order.getShopId());
                merchandiseLogService.insert(merchandiseLog);
            }

        } catch (Exception e) {
            // TODO: handle exception
            log.info("系统向erp发起采购失败，失败订单id为："+order.getId());
        }
    }

    /**
     * 保存商品日志
     *
     * @param order   订单
     * @param content 内容
     * @param remark  备注
     */
    private void saveMerchandiseLog(LitemallAdminOrder order, String content, String remark) {
    	LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
 	   	LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
 	   	merchandiseLog.setAddUserId(admin.getId());
 	   	merchandiseLog.setAdminOrderId(order.getId());
 	   	merchandiseLog.setContent(content);
 	    merchandiseLog.setRemark(remark);
 	   	merchandiseLog.setOrderSn(order.getOrderSn());
 	   	merchandiseLog.setPayPrice(order.getOrderPrice());
 	   	merchandiseLog.setShopId(order.getShopId());
 	   	merchandiseLog.setUserName(admin.getUsername());
 	   	merchandiseLogService.add(merchandiseLog);
    }

    /**
     * 订单没有通过
     * 不同意调货
     *
     * @param id     id
     * @param remark 备注
     * @return {@link Object}
     */
    public Object orderNoPass(Integer id, String remark) {

        if(ObjectUtils.isEmpty(id)){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        
        LitemallAdminOrder order = adminOrderService.queryById(id);
 	   	order.setOrderStatus(AdminOrderStatusEnum.P_6.getCode().byteValue());
 	   	adminOrderService.update(order);
 	   
 	   	//货品数量返回
 	   	// backMerchandiseNum(adminOrderVo);
 	   	//保存日志
 	   	saveMerchandiseLog(order, Constants.ORDER_NO_PASS, remark);

        return ResponseUtil.ok();
    }

    /**
     * 订单支付
     * 支付货款
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link Object}
     */
    public Object orderPay(AdminOrderVo adminOrderVo) {

        if(ObjectUtils.isEmpty(adminOrderVo.getAdminOrderId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        updateOrderStatus(adminOrderVo, AdminOrderStatusEnum.P_3.getCode().toString());
        //保存日志
        this.saveMerchandiseLog(setAdminOrder(adminOrderVo), Constants.ORDER_PAY);
        return ResponseUtil.ok();
    }

    /**
     * 发货
     * 同意发货
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link Object}
     */
    public Object deliverGoods(AdminOrderVo adminOrderVo) {

        if(ObjectUtils.isEmpty(adminOrderVo.getAdminOrderId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }

        updateOrderStatus(adminOrderVo, AdminOrderStatusEnum.P_4.getCode().toString());
        //保存日志
        this.saveMerchandiseLog(setAdminOrder(adminOrderVo), Constants.DELIVER_GOODS);
        return ResponseUtil.ok();
    }

    /**
     * 取消发货
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link Object}
     */
    public Object cancelDeliverGoods(AdminOrderVo adminOrderVo) {

        if(ObjectUtils.isEmpty(adminOrderVo.getAdminOrderId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        updateOrderStatus(adminOrderVo, AdminOrderStatusEnum.P_8.getCode().toString());
        //货品数量返回
        backMerchandiseNum(adminOrderVo);
        //保存日志
        this.saveMerchandiseLog(setAdminOrder(adminOrderVo), Constants.CANCEL_DELIVER_GOODS);
        return ResponseUtil.ok();
    }

    /**
     * 回商品num
     *
     * @param adminOrderVo 管理秩序签证官
     */
    private void backMerchandiseNum(AdminOrderVo adminOrderVo) {
        //货品数量返回
        LitemallMerchandise m = new LitemallMerchandise();
        m.setId(adminOrderVo.getMerchandiseId());
        LitemallMerchandise litemallMerchandise = merchandiseService.findById(adminOrderVo.getMerchandiseId());
        m.setNumber(litemallMerchandise.getNumber() + adminOrderVo.getNumber());
        merchandiseService.updateById(m);
    }

    /**
     * 提货
     * 确认收货
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link Object}
     */
    @Transactional
    public Object takeDelivery(AdminOrderVo adminOrderVo) {

        if(ObjectUtils.isEmpty(adminOrderVo.getAdminOrderId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        LitemallAdminOrder order = adminOrderService.queryById(adminOrderVo.getAdminOrderId());
        List<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = adminOrderMerchandiseService.querybyAdminOrderId(adminOrderVo.getAdminOrderId());
        for (LitemallAdminOrderMerchandise item : litemallAdminOrderMerchandises) {
            Integer merchandiseId = item.getMerchandiseId();
            /**
             * 给门店添加库存,存在则改变数量，不存在则新增
             */
            LitemallShopMerchandise shopMerchandise1 = shopMerchandiseService.queryByMerIdAndShopId(item.getMerchandiseId(), order.getShopId());
            if(shopMerchandise1 != null){
                shopMerchandise1.setNumber(shopMerchandise1.getNumber() + adminOrderVo.getNumber());
                shopMerchandise1.setStockNumber(shopMerchandise1.getStockNumber()+adminOrderVo.getNumber());
                shopMerchandiseService.updateById(shopMerchandise1);
            }else{
                LitemallShopMerchandise shopMerchandise = new LitemallShopMerchandise();
                LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
                shopMerchandise.setAddUserId(admin.getId());
                shopMerchandise.setMerchandiseId(merchandiseId);
                shopMerchandise.setNumber(item.getNumber());
                shopMerchandise.setSellPrice(item.getPrice());
                shopMerchandise.setShopId(order.getShopId());
                shopMerchandise.setStockNumber(shopMerchandise.getStockNumber()+item.getNumber());
                shopMerchandise.setUpdateUserId(admin.getId());
                shopMerchandiseService.create(shopMerchandise);
            }
        }

        updateOrderStatus(adminOrderVo, AdminOrderStatusEnum.P_5.getCode().toString());
        LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
        merchandiseLog.setAddUserId(order.getAdminId());
        merchandiseLog.setAdminOrderId(order.getId());
        merchandiseLog.setContent(generatorContent(Constants.TAKE_DELIVERY,order, litemallAdminOrderMerchandises));
        merchandiseLog.setOrderSn(order.getOrderSn());
        merchandiseLog.setPayPrice(order.getOrderPrice());
        merchandiseLog.setShopId(order.getShopId());
        merchandiseLog.setUserName(order.getUsername());
        merchandiseLogService.add(merchandiseLog);
        return ResponseUtil.ok();
    }

    /**
     * 读
     * 订单详情
     *
     * @param orderId 订单id
     * @param shopId  商店id
     * @return {@link Object}
     */
    public Object read(Integer orderId, Integer shopId) {
        LitemallAdminOrder litemallAdminOrder = adminOrderService.queryByIdAndShopId(orderId, shopId);
        
        //查询订单的货品列表
        List<AdminOrderMerchandiseVo> merchandises = new ArrayList<>();
        List<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = adminOrderMerchandiseService.querybyAdminOrderId(orderId);
        if(null != litemallAdminOrderMerchandises) {
        	for (LitemallAdminOrderMerchandise adminOrderMerchandise : litemallAdminOrderMerchandises) {
        		AdminOrderMerchandiseVo adminOrderMerchandiseVo = new AdminOrderMerchandiseVo();
        		adminOrderMerchandiseVo.setId(adminOrderMerchandise.getId());
        		adminOrderMerchandiseVo.setAdminOrderId(adminOrderMerchandise.getAdminOrderId());
        		Integer merchandiseId = adminOrderMerchandise.getMerchandiseId();
                adminOrderMerchandiseVo.setMerchandiseId(merchandiseId);
                adminOrderMerchandiseVo.setMerchandiseName(adminOrderMerchandise.getMerchandiseName());
                adminOrderMerchandiseVo.setMerchandiseSn(adminOrderMerchandise.getMerchandiseSn());
                adminOrderMerchandiseVo.setNumber(adminOrderMerchandise.getNumber());
                adminOrderMerchandiseVo.setPrice(adminOrderMerchandise.getPrice());
                adminOrderMerchandiseVo.setPicUrl(adminOrderMerchandise.getPicUrl());
                adminOrderMerchandiseVo.setComment(adminOrderMerchandise.getComment());
                
                LitemallMerchandise merchandise = merchandiseService.findById(merchandiseId);
                adminOrderMerchandiseVo.setBasicUnit(merchandise.getBasicUnit());
                adminOrderMerchandiseVo.setUnit(merchandise.getUnit());
                adminOrderMerchandiseVo.setRatio(merchandise.getRatio());
                adminOrderMerchandiseVo.setModel(merchandise.getModel());
                adminOrderMerchandiseVo.setStandard(merchandise.getStandard());
                
                merchandises.add(adminOrderMerchandiseVo);
			}
        	
        }
        
        //查询日志
        List<LitemallMerchandiseLog> merchandiseLogs= merchandiseLogService.queryByAdminOrderId(orderId);
        ShopOrderVo vo = new ShopOrderVo();
        vo.setMerchandises(merchandises);
        vo.setOrder(litemallAdminOrder);
        vo.setMerchandiseLogs(merchandiseLogs);
        return ResponseUtil.ok(vo);
    }


    /**
     * 设置管理秩序
     *
     * @param adminOrderVo 管理秩序签证官
     * @return {@link AdminOrderVo}
     */
    private AdminOrderVo setAdminOrder(AdminOrderVo adminOrderVo) {
        LitemallAdminOrder adminOrder = adminOrderService.queryById(adminOrderVo.getAdminOrderId());
        List<LitemallAdminOrderMerchandise> adminOrderMerchandises = adminOrderMerchandiseService.querybyAdminOrderId(adminOrder.getId());
        adminOrderVo.setAdminOrderId(adminOrder.getId());
        adminOrderVo.setMerchandiseId(adminOrderMerchandises.get(0).getMerchandiseId());
        adminOrderVo.setOrderSn(adminOrder.getOrderSn());
        adminOrderVo.setOrderPrice(adminOrder.getOrderPrice());
        adminOrderVo.setNumber(adminOrderMerchandises.get(0).getNumber());
        adminOrderVo.setShopId(adminOrder.getShopId());
        return adminOrderVo;
    }

    /**
     * 保存商品日志
     *
     * @param adminOrderVo 管理秩序签证官
     * @param content      内容
     */
    private void saveMerchandiseLog(AdminOrderVo adminOrderVo, String content) {
        //获取货品信息
        LitemallMerchandise litemallMerchandise = merchandiseService.findById(adminOrderVo.getMerchandiseId());
        LitemallAdmin admin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
        LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
        merchandiseLog.setAddUserId(admin.getId());
        merchandiseLog.setAdminOrderId(adminOrderVo.getAdminOrderId());
        merchandiseLog.setContent(content);
        merchandiseLog.setMerchandiseId(adminOrderVo.getMerchandiseId());
        merchandiseLog.setMerchandiseImage(litemallMerchandise.getPicUrl());
        merchandiseLog.setMerchandiseName(litemallMerchandise.getName());
        merchandiseLog.setMerchandiseSn(litemallMerchandise.getMerchandiseSn());
        merchandiseLog.setOrderSn(adminOrderVo.getOrderSn());
        merchandiseLog.setPayPrice(adminOrderVo.getOrderPrice());
        merchandiseLog.setPurchaseQuantity(String.valueOf(adminOrderVo.getNumber()));
        merchandiseLog.setRemainingNumber(String.valueOf(litemallMerchandise.getNumber()));
        merchandiseLog.setShopId(adminOrderVo.getShopId());
        merchandiseLog.setUserName(admin.getUsername());
        merchandiseLogService.insert(merchandiseLog);
    }

    /**
     * 更新订单状态
     *
     * @param adminOrderVo 管理秩序签证官
     * @param orderStatus  订单状态
     */
    private void updateOrderStatus(AdminOrderVo adminOrderVo, String orderStatus) {
        LitemallAdminOrder adminOrder = new LitemallAdminOrder();
        adminOrder.setId(adminOrderVo.getAdminOrderId());
        if(AdminOrderStatusEnum.P_3.getCode().toString().equals(orderStatus)){
            adminOrder.setPayStatus(Byte.valueOf(AdminPayStatusEnum.P_2.getCode().toString()));
            adminOrder.setPayTime(LocalDateTime.now());
        }
        if(AdminOrderStatusEnum.P_4.getCode().toString().equals(orderStatus)){
            adminOrder.setShipSn(adminOrderVo.getShipSn());
        }
        if(AdminOrderStatusEnum.P_8.getCode().toString().equals(orderStatus)){
            adminOrder.setOrderRemark(adminOrderVo.getRemark());
        }
        adminOrder.setOrderStatus(Byte.valueOf(orderStatus));
        adminOrderService.update(adminOrder);
    }

    /**
     * 保存管理订单商品
     *
     * @param adminOrderVo 管理秩序签证官
     * @param merchandise  商品
     * @param adminOrder   管理秩序
     */
    private void saveAdminOrderMerchandise(AdminOrderVo adminOrderVo, LitemallMerchandise merchandise, LitemallAdminOrder adminOrder) {
        LitemallAdminOrderMerchandise adminOrderMerchandise = new LitemallAdminOrderMerchandise();
        adminOrderMerchandise.setAdminOrderId(adminOrder.getId());
        adminOrderMerchandise.setMerchandiseId(adminOrderVo.getMerchandiseId());
        adminOrderMerchandise.setMerchandiseName(merchandise.getName());
        adminOrderMerchandise.setMerchandiseSn(merchandise.getMerchandiseSn());
        adminOrderMerchandise.setNumber(adminOrderVo.getNumber());
        adminOrderMerchandise.setPrice(adminOrderVo.getOrderPrice());
        adminOrderMerchandise.setPicUrl(merchandise.getPicUrl());
        adminOrderMerchandiseService.insert(adminOrderMerchandise);
    }

    /**
     * 保存管理秩序
     *
     * @param adminOrderVo 管理秩序签证官
     * @param merchandise  商品
     * @return {@link LitemallAdminOrder}
     */
    private LitemallAdminOrder saveAdminOrder(AdminOrderVo adminOrderVo, LitemallMerchandise merchandise) {
        //查询用户信息
        LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
        //查询门店信息
        LitemallShop shop = shopService.findById(adminOrderVo.getShopId());
        LitemallAdminOrder adminOrder = new LitemallAdminOrder();
        adminOrder.setAdminId(adminOrderVo.getUserId());
        adminOrder.setUsername(admin.getUsername());
        adminOrder.setShopId(adminOrderVo.getShopId());
        adminOrder.setShopName(shop.getName());
        adminOrder.setOrderRemark(adminOrderVo.getRemark());
        adminOrder.setOrderSn(RandomUtils.getMerchandiseOrderId());
        adminOrder.setConsignee(adminOrderVo.getConsignee());
        adminOrder.setMobile(adminOrderVo.getMobile());
        adminOrder.setAddress(adminOrderVo.getAddress());
        adminOrder.setUnitPrice(merchandise.getPurchasePrice());
        adminOrder.setOrderPrice(adminOrderVo.getOrderPrice());
        if(null != adminOrder.getFreightPrice()){
            adminOrder.setActualPrice(adminOrderVo.getOrderPrice().add(adminOrder.getFreightPrice()));
        }else{
            adminOrder.setActualPrice(adminOrderVo.getOrderPrice());
        }
        adminOrderService.insert(adminOrder);
        return adminOrder;
    }

    /**
     * 采购申请
     *
     * @param purchaseDto 购买dto
     * @return {@link Object}
     */
    public Object purchaseApplying(PurchaseDto purchaseDto) {
        if(ObjectUtils.isEmpty(purchaseDto.getShopId())
                || ObjectUtils.isEmpty(purchaseDto.getUserId())){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        //新增订单及子项数据
        saveAdminOrder(purchaseDto);
        return ResponseUtil.ok();
    }

    /**
     * 保存管理秩序
     *
     * @param purchaseDto 购买dto
     */
    public void saveAdminOrder(PurchaseDto purchaseDto) {
        List<LitemallAdminOrderMerchandise> rtn = new ArrayList<>();
        /**
         * 保存订单数据
         */
        //查询用户信息
        LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
        //查询门店信息
        LitemallShop shop = shopService.findById(purchaseDto.getShopId());
        LitemallAdminOrder adminOrder = new LitemallAdminOrder();
        adminOrder.setAdminId(purchaseDto.getUserId());
        adminOrder.setUsername(admin.getUsername());
        adminOrder.setShopId(purchaseDto.getShopId());
        adminOrder.setShopName(shop.getName());
        adminOrder.setOrderRemark(purchaseDto.getRemark());
        adminOrder.setOrderSn(RandomUtils.getMerchandiseOrderId());
        adminOrder.setConsignee(purchaseDto.getConsignee());
        adminOrder.setMobile(purchaseDto.getMobile());
        adminOrder.setAddress(purchaseDto.getAddress());
        adminOrder.setOrderPrice(purchaseDto.getOrderPrice());
        adminOrder.setDiscountLastPrice(purchaseDto.getOrderPrice());

        adminOrder.setOrderStatus(AdminOrderStatusEnum.P_1.getCode().byteValue());
        if(null != adminOrder.getFreightPrice()){
            adminOrder.setActualPrice(purchaseDto.getOrderPrice().add(adminOrder.getFreightPrice()));
        }else{
            adminOrder.setActualPrice(purchaseDto.getOrderPrice());
        }
        adminOrderService.insert(adminOrder);

        /**
         * 保存子项数据
         */
        if(purchaseDto.getPurchaseItemDtos() != null && purchaseDto.getPurchaseItemDtos().size() > 0){
            for(PurchaseItemDto item : purchaseDto.getPurchaseItemDtos()){
                LitemallAdminOrderMerchandise adminOrderMerchandise = new LitemallAdminOrderMerchandise();
                adminOrderMerchandise.setAdminOrderId(adminOrder.getId());
                //保存或者更新货品
                Integer merchandiseId = saveOrUpdateMerchandise(item);
                adminOrderMerchandise.setMerchandiseId(merchandiseId);
                adminOrderMerchandise.setMerchandiseName(item.getName());
                adminOrderMerchandise.setMerchandiseSn(item.getBarCode());
                adminOrderMerchandise.setNumber(item.getStock());
                adminOrderMerchandise.setPrice(item.getPrice());
                adminOrderMerchandiseService.insert(adminOrderMerchandise);
                rtn.add(adminOrderMerchandise);
            }
        }
        LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
        merchandiseLog.setAddUserId(admin.getId());
        merchandiseLog.setAdminOrderId(adminOrder.getId());
        merchandiseLog.setContent(Constants.ORDER_APPLYING);
        merchandiseLog.setRemark(purchaseDto.getRemark());
        merchandiseLog.setOrderSn(adminOrder.getOrderSn());
        merchandiseLog.setPayPrice(adminOrder.getOrderPrice());
        merchandiseLog.setShopId(adminOrder.getShopId());
        merchandiseLog.setUserName(admin.getUsername());
        merchandiseLogService.add(merchandiseLog);
    }

    /**
     * 保存或更新商品
     * 保存或者更新原料
     *
     * @param item 项
     * @return {@link Integer}
     */
    private Integer saveOrUpdateMerchandise(PurchaseItemDto item) {
    	String merchandiseSn = item.getBarCode();
    	LitemallMerchandise merchandise = merchandiseService.queryBySn(merchandiseSn);
    	if(null == merchandise) {
    		merchandise = new LitemallMerchandise();
    		merchandise.setMerchandiseSn(merchandiseSn);
    		setLitemallMerchandiseProps(merchandise, item);
    		merchandiseService.create(merchandise);
    	}else {
    		setLitemallMerchandiseProps(merchandise, item);
    		merchandiseService.updateById(merchandise);
    	}
    	return merchandise.getId();
    }

    /**
     * 设置litemall商品道具
     *
     * @param merchandise 商品
     * @param item        项
     */
    private void setLitemallMerchandiseProps(LitemallMerchandise merchandise, PurchaseItemDto item) {
    	merchandise.setName(item.getName());
    	merchandise.setBasicUnit(item.getBasicUnit());
    	merchandise.setCheckUnit(item.getCheckUnit());
    	merchandise.setUnit(item.getUnit());
    	merchandise.setCheckRatio(item.getCheckRatio());
    	merchandise.setRatio(item.getRatio());
    	merchandise.setPurchasePrice(item.getPurchasePrice());
    	merchandise.setModel(item.getModel());
    	merchandise.setStandard(item.getStandard());
    	merchandise.setPicUrl(item.getPicUrl());
    }

    /**
     * 发电机内容
     *
     * @param mark            马克
     * @param order           订单
     * @param adminOrderItems 管理订单项
     * @return {@link String}
     */
    public String generatorContent(String mark, LitemallAdminOrder order, List<LitemallAdminOrderMerchandise> adminOrderItems){
        StringBuffer buffer = new StringBuffer(mark);
        buffer.append("(");
        adminOrderItems.stream().forEach(item->{
            buffer.append("名称:").append(item.getMerchandiseName()).append(",数量:").append(item.getNumber()).append(";");
        });
        buffer.append(")");
        return buffer.toString();
    }

    /**
     * 接受审计
     *
     * @param adminOrderAcceptAuditVo 管理订单接受审计签证官
     * @return {@link Object}
     *//*
    * 收货审核
    * @return
    */
   @Transactional
   public Object acceptAudit(AdminOrderAcceptAuditVo adminOrderAcceptAuditVo) {

       if(ObjectUtils.isEmpty(adminOrderAcceptAuditVo.getAdminOrderId())|| ObjectUtils.isEmpty(adminOrderAcceptAuditVo.getShopId())){
           return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
       }
       
       Integer adminOrderId = adminOrderAcceptAuditVo.getAdminOrderId();
       LitemallAdminOrder order = adminOrderService.queryById(adminOrderId);
       if(order.getOrderStatus() != AdminOrderStatusEnum.P_4.getCode().byteValue()) {
    	   return ResponseUtil.fail(AdminResponseEnum.APPLY_AUDIT_ERROR);
       }
       
       //更新订单
       order.setOrderPrice(adminOrderAcceptAuditVo.getOrderPrice());
       order.setDiscount(adminOrderAcceptAuditVo.getDiscount());
       order.setDiscountPrice(adminOrderAcceptAuditVo.getDiscountPrice());
       order.setDiscountLastPrice(adminOrderAcceptAuditVo.getDiscountLastPrice());
       order.setActualPrice(adminOrderAcceptAuditVo.getActualPrice());
       order.setOrderStatus(Byte.valueOf(AdminOrderStatusEnum.P_7.getCode().toString()));
       adminOrderService.update(order);
       
       //更新订单原料关联表
       List<AdminOrderAcceptAuditMerchandiseVo> merchandises = adminOrderAcceptAuditVo.getMerchandises();
       for (AdminOrderAcceptAuditMerchandiseVo adminOrderAcceptAuditMerchandiseVo : merchandises) {
    	   Integer merchandiseId = adminOrderAcceptAuditMerchandiseVo.getMerchandiseId();
    	   LitemallAdminOrderMerchandise adminOrderMerchandise = adminOrderMerchandiseService.getbyAdminOrderIdAndMerchandiseId(adminOrderId, merchandiseId);
    	   
    	   adminOrderMerchandise.setNumber(adminOrderAcceptAuditMerchandiseVo.getNumber());
    	   adminOrderMerchandise.setPrice(adminOrderAcceptAuditMerchandiseVo.getPrice());
    	   adminOrderMerchandiseService.update(adminOrderMerchandise);
       }
       
       //保存日志
	   saveMerchandiseLog(order, Constants.ACCEPT_AUDIT, adminOrderAcceptAuditVo.getRemark());
       return ResponseUtil.ok();
   }

    /**
     * 通过审计
     *
     * @param adminOrderId 管理订单id
     * @param remark       备注
     * @return {@link Object}
     *//*
    * 审核通过
    * @return
    */
   @Transactional
   public Object passAudit(Integer adminOrderId, String remark) {
	   
	   if(ObjectUtils.isEmpty(adminOrderId)){
		   return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
	   }
	   
	   LitemallAdminOrder order = adminOrderService.queryById(adminOrderId);
	   if(order.getOrderStatus() != AdminOrderStatusEnum.P_4.getCode().byteValue()) {
		   return ResponseUtil.fail(AdminResponseEnum.APPLY_PURCHASE_ERROR);
	   }
	   
	   LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
       List<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = adminOrderMerchandiseService.querybyAdminOrderId(adminOrderId);
       for (LitemallAdminOrderMerchandise item : litemallAdminOrderMerchandises) {
           Integer merchandiseId = item.getMerchandiseId();
           /**
            * 给门店添加库存,存在则改变数量，不存在则新增
            */
           LitemallShopMerchandise shopMerchandise = shopMerchandiseService.queryByMerIdAndShopId(item.getMerchandiseId(), order.getShopId());
           LitemallMerchandise merchandise = merchandiseService.findById(merchandiseId);
           Double number = item.getNumber()*merchandise.getRatio();//计算入库的数量(盘点单位)
           Double basicNumber = number*merchandise.getCheckRatio();//计算入库的数量(基本单位)
           if(shopMerchandise != null){
        	   shopMerchandise.setNumber((shopMerchandise.getNumber()!=null?shopMerchandise.getNumber():0) + number);
        	   shopMerchandise.setBasicNumber((shopMerchandise.getBasicNumber()!=null?shopMerchandise.getBasicNumber():0) + basicNumber);
               shopMerchandiseService.updateById(shopMerchandise);
           }else{
               shopMerchandise = new LitemallShopMerchandise();
               shopMerchandise.setAddUserId(admin.getId());
               shopMerchandise.setMerchandiseId(merchandiseId);
               shopMerchandise.setNumber(number);
               shopMerchandise.setBasicNumber(basicNumber);
               shopMerchandise.setSellPrice(item.getPrice());
               shopMerchandise.setShopId(order.getShopId());
               shopMerchandise.setUpdateUserId(admin.getId());
               shopMerchandiseService.create(shopMerchandise);
           }
       }

       //修改订单状态为“完成”
       order.setOrderStatus(Byte.valueOf(AdminOrderStatusEnum.P_5.getCode().toString()));
       order.setEndTime(LocalDateTime.now());
       adminOrderService.update(order);
       
       //保存日志
	   saveMerchandiseLog(order, Constants.PASS_AUDIT, remark);
       return ResponseUtil.ok();
   }

    /**
     * 没有通过审核
     *
     * @param adminOrderId 管理订单id
     * @param remark       备注
     * @return {@link Object}
     *//*
    * 审核不通过
    * @return
    */
   @Transactional
   public Object noPassAudit(Integer adminOrderId, String remark) {
	   
	   if(ObjectUtils.isEmpty(adminOrderId)){
		   return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
	   }
	   
	   //修改订单状态为“待收货”
	   LitemallAdminOrder order = adminOrderService.queryById(adminOrderId);
	   if(order.getOrderStatus() != AdminOrderStatusEnum.P_4.getCode().byteValue()) {
		   return ResponseUtil.fail(AdminResponseEnum.APPLY_PURCHASE_ERROR);
	   }
	   order.setOrderStatus(AdminOrderStatusEnum.P_9.getCode().byteValue());
	   adminOrderService.update(order);
	   
	   //保存日志
	   saveMerchandiseLog(order, Constants.UN_PASS_AUDIT, remark);
	   return ResponseUtil.ok();
   }

    public Object orderHqPass(Integer id, String remark) {
        if(ObjectUtils.isEmpty(id)){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        LitemallAdminOrder order = adminOrderService.queryById(id);
        order.setOrderStatus(AdminOrderStatusEnum.P_3.getCode().byteValue());
        adminOrderService.updateById(order);
        //保存日志
        saveMerchandiseLog(order, Constants.ORDER_HQ_PASS, remark);
        //发起调货
        erpPurchase(order);
        return ResponseUtil.ok();
    }

    public Object orderHqNoPass(Integer id, String remark) {
        if(ObjectUtils.isEmpty(id)){
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        LitemallAdminOrder order = adminOrderService.queryById(id);
        order.setOrderStatus(AdminOrderStatusEnum.P_7.getCode().byteValue());
        adminOrderService.updateById(order);
        //保存日志
        saveMerchandiseLog(order, Constants.ORDER_HQ_NO_PASS, remark);
        return ResponseUtil.ok();
    }
}
